﻿using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing.Navigation;

namespace QueryDemo.ResultProviders
{
	/// <summary>
	/// Uses SharePoint Server site map provided site collection has been created from a publishing template.
	/// </summary>
	public class PortalSiteMapResultProvider : BaseResultProvider
	{
		private PortalSiteMapProvider _portalSiteMapProvider;
		private SPQuery _query;

		/// <summary>
		/// Sets properties related to use of the query within the web part.
		/// </summary>
		public PortalSiteMapResultProvider()
		{
			TypeOfQuery = QueryType.PortalSiteMapProvider;
			QueryName = "PortalSiteMapProvider";
		}

		public override bool CrossSiteCapable
		{
			get { return false; }
		}

		public override void Init()
		{
			_portalSiteMapProvider = PortalSiteMapProvider.CurrentNavSiteMapProviderNoEncode;
			_query = new SPQuery
			{
				ViewFields = GetViewFieldCaml(),
				Query = CamlQuery,
				RowLimit = (uint)RowLimit
			};
		}

		public override DataTable ExecuteQuery()
		{
			var listItemNodes = _portalSiteMapProvider.GetCachedListItemsByQuery(
				((PortalSiteMapNode)_portalSiteMapProvider.CurrentNode).WebNode,
			    ListTitle, _query, Web);
			var resultsTable = new DataTable();
			foreach (string field in ViewFields)
			{
				resultsTable.Columns.Add(field);
			}
			foreach (PortalListItemSiteMapNode node in listItemNodes)
			{
				var row = resultsTable.NewRow();
				foreach (string field in ViewFields)
				{
					row[field] = node[field];
				}
				resultsTable.Rows.Add(row);
			}
			return resultsTable;
		}
	}
}
